<template>
  <div class="app-container">
    <h1 style="text-align: center;">DeepLink 自动转换工具</h1>
    <el-form ref="form" :model="form" class="form-container">
      <el-form-item>
        <el-input v-model="form.name" :rows="6" type="textarea" placeholder="请输入淘宝 DeepLink" />
      </el-form-item>
      <el-form-item style="text-align: center;">
        <el-button type="primary" @click="onSubmit">转换</el-button>
      </el-form-item>
    </el-form>

    <h1 style="text-align: center;">转换结果：</h1>
    <el-input
      v-model="data"
      :rows="6"
      type="textarea"
      placeholder="转换后的链接将显示在这里"
      readonly
      class="result-input"
    />

    <el-button type="success" style="display: block; margin: 20px auto;" @click="copyText">
      一键复制
    </el-button>

    <el-message v-if="copySuccess" type="success" show-close>
      复制成功！
    </el-message>
  </div>
</template>

<script>
import { Message } from 'element-ui'
export default {
  data() {
    return {
      form: {
        name: ''
      },
      data: '',
      copySuccess: false
    }
  },
  methods: {
    async onSubmit() {
      const originalUrl = this.form.name.trim()
      console.log('用户输入的淘宝 DeepLink:', originalUrl)

      if (!originalUrl) {
        this.data = '请输入有效的 DeepLink！'
        return
      }

      try {
        // https://gitee.com/chuaishoushou/DeepLinkAPI
        const response = await fetch('http://www.xiaogao.site:8700/api/v1/dplink/taobao', {
          method: 'POST', // 明确指定使用 POST 请求
          headers: {
            'Content-Type': 'application/json',
            'Accept': 'application/json'
          },
          body: JSON.stringify({ url: originalUrl }) // 发送 JSON 数据
        })

        if (!response.ok) {
          throw new Error(`HTTP 错误！状态码: ${response.status}`)
        }

        const result = await response.json()
        console.log('后端返回:', result)

        if (result.success) {
          Message({
            message: '转换成功！',
            type: 'success'
          })
          this.data = result.data // 直接赋值转换后的 URL
        } else {
          this.data = `转换失败: ${result.data}`
        }
      } catch (error) {
        console.error('请求出错:', error)
        this.data = '转换时发生错误，请检查控制台输出。'
      }
    },
    copyText() {
      navigator.clipboard.writeText(this.data).then(() => {
        this.copySuccess = true
        setTimeout(() => {
          this.copySuccess = false
        }, 2000)
      }).catch((error) => {
        console.error('复制失败:', error)
      })
    }
  }
}
</script>

<style scoped>
.app-container {
  max-width: 600px;
  margin: 40px auto;
  padding: 20px;
  border: 1px solid #ddd;
  border-radius: 8px;
  background: #f9f9f9;
}

.form-container {
  padding: 30px;
}

.result-input {
  cursor: text;
  word-wrap: break-word;
  white-space: pre-wrap;
  overflow-wrap: break-word;
  width: 100%;
  margin: 0 auto;
}
</style>
